<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>欢迎回来</h2>
        <p>登录账号，继续使用我们的服务</p>
      </div>

      <form class="login-form" @submit.prevent="handleLogin">
        <!-- 用户名密码登录表单 -->
        <template v-if="!isPhoneLogin">
          <div class="form-group" :class="{ 'error': usernameError }">
            <label for="username" class="form-label">用户名</label>
            <input
              id="username"
              v-model="username"
              type="text"
              placeholder="请输入用户名"
              class="form-input"
              required
            />
            <div v-if="usernameError" class="error-message">{{ usernameError }}</div>
          </div>

          <div class="form-group" :class="{ 'error': passwordError }">
            <label for="password" class="form-label">密码</label>
            <input
              id="password"
              v-model="password"
              type="password"
              placeholder="请输入密码"
              class="form-input"
              required
            />
            <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
          </div>

          <div class="form-options">
            <div class="form-checkbox">
              <input id="remember" v-model="rememberMe" type="checkbox" />
              <label for="remember">记住我</label>
            </div>
            <a href="#" class="forgot-password">忘记密码？</a>
          </div>

          <!-- 通用错误消息显示区域 -->
          <div v-if="error" class="error-message general-error">
            {{ error }}
          </div>

          <button type="submit" class="btn-login">登录</button>
        </template>

        <!-- 手机号登录表单 -->
        <template v-else>
          <div class="form-group" :class="{ 'error': phoneError }">
            <label for="phone" class="form-label">手机号</label>
            <input
              id="phone"
              v-model="phone"
              type="tel"
              placeholder="请输入手机号"
              class="form-input"
              required
            />
            <div v-if="phoneError" class="error-message">{{ phoneError }}</div>
          </div>

          <div class="form-group" :class="{ 'error': smsCodeError }">
            <label for="smsCode" class="form-label">验证码</label>
            <div class="sms-code-wrapper">
              <input
                id="smsCode"
                v-model="smsCode"
                type="text"
                placeholder="请输入验证码"
                class="form-input"
                required
              />
              <button 
                type="button" 
                class="send-sms-btn"
                :disabled="isSendingCode"
                @click="sendSmsCode"
              >
                {{ isSendingCode ? `${countdown}秒后重发` : '获取验证码' }}
              </button>
            </div>
            <div v-if="smsCodeError" class="error-message">{{ smsCodeError }}</div>
          </div>

          <!-- 通用错误消息显示区域 -->
          <div v-if="error" class="error-message general-error">
            {{ error }}
          </div>

          <button type="submit" class="btn-login" @click.stop="handlePhoneSubmit">手机号登录</button>
          
          <button type="button" class="switch-login-mode" @click="isPhoneLogin = false">
            使用用户名密码登录
          </button>
        </template>

        <div v-if="!isPhoneLogin" class="login-divider">
          <span>或</span>
        </div>

        <div class="social-login">
          <button type="button" class="social-button" @click="handleSocialLogin('qq')">
            <i class="fa fa-qq"></i>
            <span>QQ登录</span>
          </button>
          <button type="button" class="social-button" @click="handleSocialLogin('wechat')">
            <i class="fa fa-weixin"></i>
            <span>微信登录</span>
          </button>
          <button type="button" class="social-button" @click="handlePhoneLogin">
            <i class="fa fa-mobile"></i>
            <span>手机号登录</span>
          </button>
        </div>

        <div class="register-link">
          <p>还没有账号？<router-link to="/register">立即注册</router-link></p>
        </div>
      </form>

      <div class="login-footer">
        <p>登录即表示您同意我们的<a href="#">服务条款</a>和<a href="#">隐私政策</a></p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LoginView',
  data() {
    return {
      username: '',
      password: '',
      rememberMe: false,
      error: '',
      usernameError: '',
      passwordError: '',
      isLoading: false,
      isPhoneLogin: false,
      phone: '',
      smsCode: '',
      phoneError: '',
      smsCodeError: '',
      isSendingCode: false,
      countdown: 60,
    }
  },
  mounted() {
    // 首次打开页面应该显示登录页面，即使有保存的用户信息
    // 只有在用户点击登录按钮后才应该跳转
  },
  methods: {
    validateForm() {
      let isValid = true
      this.usernameError = ''
      this.passwordError = ''
      this.error = ''

      // 验证用户名
      if (!this.username.trim()) {
        this.usernameError = '请输入用户名'
        isValid = false
      }

      // 验证密码
      if (!this.password) {
        this.passwordError = '请输入密码'
        isValid = false
      }

      return isValid
    },

    handleLogin() {
      // 表单验证
      if (!this.validateForm()) {
        return
      }

      // 检查是否是管理员账号登录
      const isAdminAccount = this.username === 'admin' && this.password === 'admin123'
      
      if (isAdminAccount) {
        // 设置管理员登录状态
        const adminUser = {
          username: 'admin',
          role: 'admin',
        }
        // 清除普通用户登录状态，避免状态冲突
        localStorage.removeItem('currentUser')
        localStorage.removeItem('rememberMe')
        // 设置管理员登录信息
        localStorage.setItem('adminLoggedIn', 'true')
        localStorage.setItem('adminUser', JSON.stringify(adminUser))
        
        // 跳转到后台管理控制台
        this.$router.push('/admin/dashboard')
      } else {
        // 验证普通用户账号和密码是否已注册
        const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
        const user = registeredUsers.find(
          u => u.username === this.username && u.password === this.password,
        )
        
        if (user) {
          // 确保用户对象包含所有必要的字段和默认值
          const userWithDefaults = {
            ...user,
            following: user.following || 0,
            followers: user.followers || 0,
            coins: user.coins || 0,
            level: user.level || 0,
            vip: user.vip || false,
            totalPlays: user.totalPlays || 0,
            videos: user.videos || [],
            drafts: user.drafts || [],
          }
          
          // 设置普通用户登录状态和记住我状态
          localStorage.setItem('currentUser', JSON.stringify(userWithDefaults))
          localStorage.setItem('rememberMe', this.rememberMe)
          
          // 通知App组件更新登录状态
          if (window.appInstance) {
            window.appInstance.checkLoginStatus()
          }
          
          // 跳转到首页
          this.$router.push('/')
        } else {
          this.error = '用户名或密码错误，请使用已注册的账号登录'
        }
      }
    },
    handleSocialLogin(provider) {
      console.log('社交登录:', provider)
      // 模拟社交登录成功，确保包含所有必要的默认值
      const socialUser = {
        username: `${provider.charAt(0).toUpperCase() + provider.slice(1)}用户`,
        avatar: `https://placehold.co/40x40/FB7299/FFFFFF?text=${provider.charAt(0).toUpperCase()}`,
        following: 0,
        followers: 0,
        coins: 0,
        level: 0,
        vip: false,
        totalPlays: 0,
        videos: [],
        drafts: [],
      }
      
      // 设置登录状态
      localStorage.setItem('currentUser', JSON.stringify(socialUser))
      localStorage.setItem('rememberMe', this.rememberMe)
      
      // 通知App组件更新登录状态
      if (window.appInstance) {
        window.appInstance.checkLoginStatus()
      }
      
      // 跳转到首页
      this.$router.push('/')
    },
    handlePhoneLogin() {
      // 手机号登录处理逻辑
      console.log('使用手机号登录')
      // 可以在这里切换到手机号登录表单或跳转到手机号登录页面
      this.isPhoneLogin = true
    },
    handlePhoneSubmit(e) {
      e.preventDefault()
      // 重置错误信息
      this.phoneError = ''
      this.smsCodeError = ''
      this.error = ''
      
      // 验证手机号
      if (!this.phone) {
        this.phoneError = '请输入手机号'
        return
      }
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        this.phoneError = '请输入正确的手机号'
        return
      }
      
      // 验证验证码
      if (!this.smsCode) {
        this.smsCodeError = '请输入验证码'
        return
      }
      if (!/^\d{6}$/.test(this.smsCode)) {
        this.smsCodeError = '验证码为6位数字'
        return
      }
      
      // 模拟登录请求
      this.isLoading = true
      setTimeout(() => {
        this.isLoading = false
        console.log('手机号登录成功，手机号：', this.phone)
        this.$router.push('/')
      }, 1500)
    },
    sendSmsCode() {
      // 验证手机号
      if (!this.phone) {
        this.phoneError = '请输入手机号'
        return
      }
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        this.phoneError = '请输入正确的手机号'
        return
      }
      
      // 模拟发送验证码
      this.isSendingCode = true
      this.countdown = 60
      
      console.log('向手机号', this.phone, '发送验证码')
      
      // 倒计时
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.isSendingCode = false
          this.countdown = 60
        }
      }, 1000)
    },
  },
}
</script>

<style scoped>
/* 登录页面样式优化 - 基于ll.html设计风格 */
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: var(--bg-color, #F5F5F5);
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.login-box {
  background-color: var(--card-bg, #FFFFFF);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  padding: 30px;
  width: 100%;
  max-width: 400px;
  transform: translateY(0);
  transition: transform 0.3s ease;
}

.login-header {
  text-align: center;
  margin-bottom: 25px;
}

.login-header h2 {
  font-size: 24px;
  font-weight: bold;
  color: var(--text-color, #212121);
  margin: 0;
}

.login-header p {
  font-size: 14px;
  color: var(--text-secondary, #999999);
  margin: 8px 0 0;
}

.login-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color, #212121);
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  height: 44px;
  padding: 0 15px;
  border: 1px solid var(--border-color, #EEEEEE);
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background-color: var(--card-bg, #FFFFFF);
  color: var(--text-color, #212121);
}

.form-input:focus {
  outline: none;
  border-color: var(--primary-color, #FB7299);
  box-shadow: 0 0 0 3px var(--hover-color, rgba(251, 114, 153, 0.2));
}

.form-group.error .form-input {
  border-color: #FF4D4F;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.form-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-checkbox input[type="checkbox"] {
  width: 16px;
  height: 16px;
  accent-color: var(--primary-color, #FB7299);
  margin: 0;
}

.form-checkbox label {
  font-size: 14px;
  color: var(--text-secondary, #999999);
  cursor: pointer;
  margin: 0;
}

.forgot-password {
  font-size: 14px;
  color: var(--secondary-color, #23ADE5);
  text-decoration: none;
}

.forgot-password:hover {
  text-decoration: underline;
}

.error-message {
  color: #FF4D4F;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.general-error {
  padding: 12px;
  background-color: #FFF1F0;
  border: 1px solid #FFCCC7;
  border-radius: 8px;
  margin-bottom: 16px;
  font-size: 14px;
}

.btn-login {
  width: 100%;
  height: 44px;
  background-color: var(--primary-color, #FB7299);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-login:hover {
  background-color: #E96385;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(251, 114, 153, 0.3);
}

.btn-login:disabled {
  background-color: var(--text-secondary, #999999);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.sms-code-wrapper {
  display: flex;
  gap: 10px;
}

.sms-code-wrapper .form-input {
  flex: 1;
}

.send-sms-btn {
  padding: 10px 16px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
}

.send-sms-btn:hover:not(:disabled) {
  background-color: #1e88e5;
}

.send-sms-btn:disabled {
  background-color: var(--text-secondary, #999999);
  cursor: not-allowed;
}

.switch-login-mode {
  margin-top: 15px;
  padding: 10px;
  background: none;
  border: none;
  color: #2196f3;
  cursor: pointer;
  font-size: 14px;
  text-align: center;
  width: 100%;
}

.switch-login-mode:hover {
  text-decoration: underline;
}

.login-divider {
  display: flex;
  align-items: center;
  margin: 25px 0;
}

.login-divider::before,
.login-divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background-color: var(--border-color, #EEEEEE);
}

.login-divider span {
  padding: 0 15px;
  font-size: 14px;
  color: var(--text-secondary, #999999);
}

.social-login {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  justify-content: center;
}

.social-button {
  width: 80px;
  height: 80px;
  border: 1px solid var(--border-color, #EEEEEE);
  background-color: var(--card-bg, #FFFFFF);
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 5px;
  font-size: 14px;
  transition: all 0.3s ease;
  color: var(--text-color, #212121);
  position: relative;
  z-index: 1;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
}

.social-button i {
  font-size: 24px;
}

.social-button:hover {
  background-color: var(--bg-color, #F5F5F5);
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.social-button:nth-child(1):hover {
  border-color: #07C160;
  color: #07C160;
}

.social-button:nth-child(2):hover {
  border-color: #12B7F5;
  color: #12B7F5;
}

.social-button:nth-child(3):hover {
  border-color: #E6162D;
  color: #E6162D;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: var(--text-secondary, #999999);
  margin-bottom: 15px;
}

.register-link a {
  color: var(--primary-color, #FB7299);
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

.login-footer {
  text-align: center;
}

.login-footer p {
  font-size: 12px;
  color: var(--text-secondary, #999999);
  margin: 0;
  line-height: 1.6;
}

.login-footer a {
  color: var(--primary-color, #FB7299);
  text-decoration: none;
}

.login-footer a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .login-box {
    padding: 25px 20px;
  }
  
  .login-header h2 {
    font-size: 22px;
  }
  
  .social-login {
    gap: 8px;
  }
}
</style>